package com.mg.plugin.agrometeorology.model;

import com.mg.model.Model;
import com.mg.model.Param;
import com.mg.model.Port;
import com.mg.plugin.agrometeorology.common.MathCalculator;
import com.mg.plugin.agrometeorology.entity.WeaData;
import com.mg.pluginexample2.ModuleBase;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class ProductionForecastBaseSuitabilityDataAssistModel extends ModuleBase {

    public ProductionForecastBaseSuitabilityDataAssistModel(int nID) {
        super(nID);
        m_alInputPort.add(new Port(this, Port.Type.Unknown));
        m_alInputPort.add(new Port(this, Port.Type.Unknown));
        m_alOutputPort.add(new Port(this, Port.Type.Unknown));
    }

    public String GetGroupName() {
        return "产量预报";
    }

    public String GetName() {
        return "基于气象适宜度方法(计算)";
    }

    public String GetDescription() {
        return "基于气象适宜度方法（数据必须是同一年的）";
    }

    public boolean OnAttach(Port portFrom, Port portTo) {
        try {
            int i = FindPort(portFrom, false);
            if (i != -1) {
                return true;
            }
            i = FindPort(portTo, true);
            if (i == -1) {
                return false;
            }

            ArrayList<Param> alParam = new ArrayList<Param>();
            portFrom.GetModule().GetOutputParam(portFrom, alParam);

            if (alParam.size() != 1) {
                return false;
            }

            if (alParam.get(0).m_objValue != null && !(alParam.get(0).m_objValue instanceof ArrayList)) {
                m_model.OutputLog(Model.LogLevel.Info, "alParam.get(0).m_objValue != null && !(alParam.get(0).m_objValue instanceof ArrayList)");
                return false;
            }
            if (i == 0) {
                m_model.OutputLog(Model.LogLevel.Info, "SET m_inputStationDataList");
                m_inputStationDataList = (List<String>) alParam.get(0).m_objValue;
            }
            if (i == 1) {
                m_model.OutputLog(Model.LogLevel.Info, "m_inputRealityList" + alParam.get(0).m_objValue.getClass());
                m_inputRealityList = (List<String>) alParam.get(0).m_objValue;
            }

            portTo.SetType(portFrom.GetType());
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean OnDetach(Port portFrom, Port portTo) {
        if (!super.OnDetach(portFrom, portTo))
            return false;
        try {
            int i = FindPort(portTo, true);
            if (i == -1)
                return true;
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    //用于 参数->XML 等
    public int GetParam(ArrayList<Param> alParam) {
        try {
            super.GetParam(alParam);
            alParam.add(new Param("Date", m_strDate, "时间对应字段", "Date", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("CornRValue", m_strCornRValue, "玉米气象适宜度", "Precipitation", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("BeanRValue", m_strBeanRValue, "大豆气象适宜度", "Temperature", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("RiceRValue", m_strRiceRValue, "水稻气象适宜度", "SunshineHour", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("m_strDadou", m_strDadou, "大豆单产", "m_strDadou", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("m_strYumi", m_strYumi, "玉米单产", "m_strYumi", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("m_strShuiDao", m_strShuiDao, "水稻单产", "m_strShuiDao", "参数匹配", Param.EditType.Default));
            alParam.add(new Param("m_strStartTime", m_strStartTime, "数据开始时间", "Time", "时间", Param.EditType.Default));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return alParam.size();
    }

    public boolean OnParamChanged(ArrayList<Param> alParam, int nIndex, Object objValue) {
        return super.OnParamChanged(alParam, nIndex, objValue);
    }

    //用于 XML->参数 等
    public int SetParam(final ArrayList<Param> alParam) {
        int i = super.SetParam(alParam);
        try {
            m_strDate = (String) alParam.get(i++).m_objValue;
            m_strCornRValue = (String) alParam.get(i++).m_objValue;
            m_strBeanRValue = (String) alParam.get(i++).m_objValue;
            m_strRiceRValue = (String) alParam.get(i++).m_objValue;
            m_strDadou = (String) alParam.get(i++).m_objValue;
            m_strYumi = (String) alParam.get(i++).m_objValue;
            m_strShuiDao = (String) alParam.get(i++).m_objValue;
            m_strStartTime = (String) alParam.get(i++).m_objValue;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return i;
    }

    public int GetOutputParam(Port port, ArrayList<Param> alParam) {
        int i = FindPort(port, false);
        if (i == -1) {
            return 0;
        }

        alParam.add(new Param("ResultString", m_listCSV));
        return alParam.size();
    }

    @SuppressWarnings("static-access")
    public boolean Execute() {
        if (m_inputRealityList != null && m_inputRealityList.size() >= 2) {
            m_inputRealityList.remove(1);
            m_inputRealityList.remove(0);
            m_inputStationDataList.addAll(m_inputRealityList);
        }

        m_listCSV.clear();
        String head = "id,endDate,forecastType,dadouForecastRate,yumiForecastRate,shuidaoForecastRate,dadouForecast,yumiForecast,shuidaoForecast,dadouFiveForecastRate,yumiFiveForecastRate,shuidaoFiveForecastRate";
        String type = "String,String,String,Double,Double,Double,Double,Double,Double,Double,Double,Double";
        m_listCSV.add(head);
        m_listCSV.add(type);
        WeaData calcWeaData = null;
        List<WeaData> weaDataList = new ArrayList<WeaData>();

        SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
        String str = m_strStartTime.replace("$ThisYear", sdfYear.format(m_model.m_dateDataStart));
        str = str.replace("$DateStart", sdfDate.format(m_model.m_dateDataStart));
        m_model.OutputLog(Model.LogLevel.Info, "STR" + str);
        Calendar dateNow = Calendar.getInstance();
        setDate(dateNow, sdfDate, str);

        if (m_inputStationDataList != null && m_inputStationDataList.size() > 0) {
            String foreHeader = m_inputStationDataList.get(0);
            if (!verifyHeader(foreHeader)) {
                m_model.OutputLog(Model.LogLevel.Error, "Header Can Not Match!");
                return false;
            } else {
                calcWeaData = formatStationData(m_inputStationDataList, foreHeader, weaDataList, dateNow, sdfDate);
            }
        } else {
            return false;
        }

        double[][] beanVir = new double[2][3];
        double[][] cornVir = new double[2][3];
        double[][] riceVir = new double[2][3];
        for (int i = 0; i < 2; i++) {
            WeaData tmp = weaDataList.get(i);
            beanVir[i][0] = tmp.getBeanRValue();
            beanVir[i][1] = 1;
            beanVir[i][2] = tmp.getDadou();

            cornVir[i][0] = tmp.getCornRValue();
            cornVir[i][1] = 1;
            cornVir[i][2] = tmp.getYumi();

            riceVir[i][0] = tmp.getRiceRValue();
            riceVir[i][1] = 1;
            riceVir[i][2] = tmp.getShuidao();
        }
        WeaData oldWeaData = weaDataList.get(0);
        double[] forecastRate = calcForecastRate(beanVir, cornVir, riceVir, calcWeaData, oldWeaData);

        double[] fiveYield = calcYield(weaDataList);
        String id = str + "_SUIT";


        String data = id + "," + str + "," + "SUIT," + forecastRate[0] + "," + forecastRate[1] + "," + forecastRate[2]
                + "," + oldWeaData.getDadou() * (1 + forecastRate[0])
                + "," + oldWeaData.getYumi() * (1 + forecastRate[1])
                + "," + oldWeaData.getShuidao() * (1 + forecastRate[2])
                + "," + (oldWeaData.getDadou() * (1 + forecastRate[0]) - fiveYield[0]) / fiveYield[0]
                + "," + (oldWeaData.getYumi() * (1 + forecastRate[1]) - fiveYield[1]) / fiveYield[1]
                + "," + (oldWeaData.getShuidao() * (1 + forecastRate[2]) - fiveYield[2]) / fiveYield[2];
        m_listCSV.add(data);
        OnParamChanged();
        return true;
    }

    private double[] calcForecastRate(double[][] beanVir, double[][] cornVir, double[][] riceVir, WeaData calcWeaData, WeaData oldWeaData) {
        double[] bean = MathCalculator.calcDeterminant(beanVir);
        double[] corn = MathCalculator.calcDeterminant(cornVir);
        double[] rice = MathCalculator.calcDeterminant(riceVir);
        double dRate = bean[0] * calcWeaData.getBeanRValue() + bean[1];
        double yRate = corn[0] * calcWeaData.getCornRValue() + corn[1];
        double sRate = rice[0] * calcWeaData.getRiceRValue() + rice[1];


        dRate = (dRate - oldWeaData.getDadou()) / oldWeaData.getDadou();
        yRate = (yRate - oldWeaData.getYumi()) / oldWeaData.getYumi();
        sRate = (sRate - oldWeaData.getShuidao()) / oldWeaData.getShuidao();
        double d = new BigDecimal(dRate).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
        double y = new BigDecimal(yRate).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
        double s = new BigDecimal(sRate).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
        double[] res = {dRate - d, yRate - y, sRate - s};
        return res;
    }

    private double[] calcYield(List<WeaData> weaDataList) {
        double beanRate = 0;
        double cornRate = 0;
        double riceRate = 0;
        for (WeaData weaData : weaDataList) {
            beanRate += weaData.getDadou();
            cornRate += weaData.getYumi();
            riceRate += weaData.getShuidao();
        }
        double[] rate = {beanRate / 5, cornRate / 5, riceRate / 5};
        return rate;
    }

    private void setDate(Calendar dateNow, SimpleDateFormat sdfDate, String str) {
        try {
            dateNow.setTime(sdfDate.parse(str));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private WeaData formatStationData(List<String> inputRealityList, String realHeader, List<WeaData> weaDataList, Calendar dateNow, SimpleDateFormat sdfDate) {
        WeaData resWeaData = null;
        Calendar calendar = Calendar.getInstance();
        int realDateIndex = findDataIndex(realHeader, m_strDate);

        int realBeanRValueIndex = findDataIndex(realHeader, m_strBeanRValue);
        int realCornRValueIndex = findDataIndex(realHeader, m_strCornRValue);
        int realRiceRValueIndex = findDataIndex(realHeader, m_strRiceRValue);


        int realDadouIndex = findDataIndex(realHeader, m_strDadou);
        int realYumiIndex = findDataIndex(realHeader, m_strYumi);
        int realShuiDaoIndex = findDataIndex(realHeader, m_strShuiDao);

        String date = "";
        int yearNow = dateNow.get(Calendar.YEAR);
        for (int i = 2; i < inputRealityList.size(); i++) {
            String[] data = inputRealityList.get(i).split(",");

            date = data[realDateIndex];
            setDate(calendar, sdfDate, date);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int month = calendar.get(Calendar.MONTH);
            int year = calendar.get(Calendar.YEAR);

            WeaData weaData = new WeaData();
            weaData.setDate(date);
            weaData.setYear(String.valueOf(year));
            weaData.setMMDD(month + "-" + day);
            weaData.setBeanRValue(Float.parseFloat(data[realBeanRValueIndex]));
            weaData.setCornRValue(Float.parseFloat(data[realCornRValueIndex]));
            weaData.setRiceRValue(Float.parseFloat(data[realRiceRValueIndex]));

            if (!data[realDadouIndex].equals("null")) {
                weaData.setDadou(Float.parseFloat(data[realDadouIndex]));
                weaData.setYumi(Float.parseFloat(data[realYumiIndex]));
                weaData.setShuidao(Float.parseFloat(data[realShuiDaoIndex]));
            }

            if (yearNow == year) {
                resWeaData = weaData;
            } else {
                weaDataList.add(weaData);
            }

        }
        return resWeaData;
    }

    /**
     * 表头检验
     *
     * @param realHeader 实况数据表头
     * @return
     */
    private boolean verifyHeader(String realHeader) {

        if (realHeader.contains(m_strDate) && realHeader.contains(m_strDadou)) {
            if (realHeader.contains(m_strYumi) && realHeader.contains(m_strShuiDao)) {
                return true;
            }
        }
        return false;
    }

    private int findDataIndex(String realHeader, String strRain) {

        String[] data = realHeader.split(",");
        for (int i = 0; i < data.length; i++) {
            if (data[i].equalsIgnoreCase(strRain)) {
                return i;
            }
        }
        return -1;
    }

    private List<String> m_inputStationDataList = new ArrayList<String>();
    private List<String> m_inputRealityList = new ArrayList<String>();
    private List<String> m_listCSV = new ArrayList<String>();

    private String m_strDate;
    private String m_strCornRValue;
    private String m_strYumiRain;
    private String m_strShuiRain;
    private String m_strBeanRValue;
    private String m_strYumiTemp;
    private String m_strShuiTemp;
    private String m_strRiceRValue;
    private String m_strYumiSun;
    private String m_strShuiSun;
    private String m_strDadou;
    private String m_strYumi;
    private String m_strShuiDao;
    private String m_strStartTime;
}
